---
title: Frontend Tools
icon: "lucide/Wrench"
description: Create frontend tools and use them within your LlamaIndex agent.
---
import { IframeSwitcher } from "@/components/content"
import RunAndConnect from "@/snippets/integrations/llamaindex/run-and-connect.mdx"

<IframeSwitcher
  id="frontend-tools-example"
  exampleUrl="https://feature-viewer.copilotkit.ai/llama-index/feature/agentic_chat?sidebar=false&chatDefaultOpen=false"
  codeUrl="https://feature-viewer.copilotkit.ai/llama-index/feature/agentic_chat?view=code&sidebar=false&codeLayout=tabs"
  exampleLabel="Demo"
  codeLabel="Code"
  height="700px"
/>

## What is this?
Frontend tools enable you to define client-side functions that your LlamaIndex agent can invoke, with execution happening entirely in the user's browser. When your agent calls a frontend tool,
the logic runs on the client side, giving you direct access to the frontend environment.

This can be utilized to let [your agent control the UI](/llamaindex/frontend-actions), [generative UI](/llamaindex/generative-ui/frontend-tools), or for Human-in-the-loop interactions.

In this guide, we cover the use of frontend tools for generative UI.

## When should I use this?
Use frontend tools when you need your agent to interact with client-side primitives such as:
- Reading or modifying React component state
- Accessing browser APIs like localStorage, sessionStorage, or cookies
- Triggering UI updates or animations
- Interacting with third-party frontend libraries
- Performing actions that require the user's immediate browser context

## Implementation

<Steps>
    <Step>
      ### Run and connect your agent
      <RunAndConnect components={props.components} />
    </Step>

    <Step>
        ### Create a frontend tool

        First, you'll need to create a frontend tool using the [useFrontendTool](/reference/hooks/useFrontendTool) hook. Here's a simple one to get you started
        that says hello to the user.

        ```tsx title="page.tsx"
        import { useFrontendTool } from "@copilotkit/react-core" // [!code highlight]

        export function Page() {
          // ...

          // [!code highlight:25]
          useFrontendTool({
            name: "sayHello",
            description: "Say hello to the user",
            parameters: [
              {
                name: "name",
                type: "string",
                description: "The name of the user to say hello to",
                required: true,
              },
            ],
            handler({ name }) {
              // Handler returns the result of the tool call
              return `Hello, ${name}!`;
            },
            render: ({ args }) => {
              // Renders UI based on the data of the tool call
              return (
                <div>
                  <h1>Hello, {args.name}!</h1>
                  <h1>{`You're currently on ${window.location.href}`}</h1>
                </div>
              );
            },
          });

          // ...
        }
        ```
    </Step>
    <Step>
        ### Add the tool to your agent

        Add the frontend tool to your agent so it knows about it. Since the tool will be executed in the frontend,
        we'll add it to the `frontend_tools` list.

        ```python title="agent.py"
        from fastapi import FastAPI
        from llama_index.llms.openai import OpenAI
        from llama_index.protocols.ag_ui.router import get_ag_ui_workflow_router

        def sayHello(name: str) -> str:
            """Says hello to the user and takes the name as an argument."""
            return f"Hello, {name}!"

        # Initialize the LLM
        llm = OpenAI(model="gpt-4o")

        # Create the AG-UI workflow router
        agentic_chat_router = get_ag_ui_workflow_router(
            llm=llm,
            frontend_tools=[sayHello],
            system_prompt="You are a helpful AI assistant with access to various tools and capabilities.",
        )

        # Create FastAPI app
        app = FastAPI(
            title="LlamaIndex Agent",
            description="A LlamaIndex agent integrated with CopilotKit",
            version="1.0.0"
        )

        # Include the router
        app.include_router(agentic_chat_router)

        # Health check endpoint
        @app.get("/health")
        async def health_check():
            return {"status": "healthy", "agent": "llamaindex"}

        if __name__ == "__main__":
            import uvicorn
            uvicorn.run(app, host="localhost", port=8000)
        ```
    </Step>
    <Step>
        ### Give it a try!
        You've now given your agent the ability to directly call any frontend tools you've defined. These tools will be available to the agent where they can be used as needed.
    </Step>
</Steps>
